<?php defined('SYSPATH') or die('No direct script access.');

class PaymentAcceptance_Controller extends OrgController {

    public function __construct() {
        parent::__construct();
        $this->activeMenuItem = OrgMenu::$SEMINARS;
    }

    public function edit() {
        $seminarId = $this->input->get('id');
        if (! valid::isId($seminarId)) {
            $this->msg->error('error.invalidId');
            $this->redirect('/org/orgSeminar/all');
        }
        
        $seminar = $this->dao->getLocalizedEntityById('seminar', $seminarId, $this->getL10nLanguageCode());
        if (! $seminar) {
            $this->msg->error('error.invalidId');
            $this->redirect('/org/orgSeminar/all');
        }
        
        $this->viewData['seminar'] = $seminar;

        $seminarPayment = $this->dao->getPaymentAcceptance($seminarId, $this->getAuthOrg('id'));
        if ($seminarPayment == NULL) {
            // Set default values
            $seminarPayment = array();
            $seminarPayment['seminar_id'] = $seminarId;
            $seminarPayment['accepts_cash'] = sql::$FALSE;
            $seminarPayment['accepts_bank_transfer'] = sql::$FALSE;
        }
        $this->viewData['paymentAcceptance'] = $seminarPayment;

        $this->loadFormData();
        $this->renderSubview('org/paymentAcceptance/paymentAcceptanceEdit');
    }
    
    protected function loadFormData() {
        $this->viewData['bankAccountOptions'] = $this->dao->queryOptions(
                'SELECT id, name FROM bank_account WHERE organization_id = :organization_id AND enabled = :enabled ORDER BY name ASC',
                array('organization_id' => $this->getAuthOrg('id'), 'enabled' => sql::$TRUE));
    }

    public function save() {
        $form = $this->postToDbValues();
        $form['organization_id'] = $this->getAuthOrg('id');

        $this->viewData['paymentAcceptance'] = $form;
        
        $seminar = $this->dao->getLocalizedEntityById('seminar', $form['seminar_id'], $this->getL10nLanguageCode());
        if (! $seminar) {
            $this->msg->error('error.invalidId');
            $this->redirect('/org/orgSeminar/all');
        }
        $this->viewData['seminar'] = $seminar;
        
        $oldRecord = $this->dao->getUnique('payment_acceptance', array('seminar_id' => $seminar['id'], 'organization_id' => $this->getAuthOrg('id')));

        if ($seminar['active'] && $oldRecord) {
            // The following fields are disabled, so fill them with the old values
            if ($oldRecord['accepts_bank_transfer']) {
                $form['accepts_bank_transfer'] = $oldRecord['accepts_bank_transfer'];
                $form['variable_symbol'] = $oldRecord['variable_symbol'];
                $form['bank_account_id'] = $oldRecord['bank_account_id'];
            }
            if ($oldRecord['accepts_cash']) {
                $form['accepts_cash'] = $oldRecord['accepts_cash'];
            }
            
            $this->viewData['paymentAcceptance'] = $form;
        }
        
        // Basic validation
        $validator = new EntityValidator($form, 'paymentAcceptance', $this->msg);
        $validator->date('deadline');
        
        $validator->boolean('accepts_cash');
        $validator->boolean('accepts_bank_transfer');
        
        if ($form['accepts_cash'] == sql::$TRUE) {
            $validator->required('cash_notes');
        }
        if ($form['accepts_bank_transfer'] == sql::$TRUE) {
            $validator->id('bank_account_id');
            $validator->required('variable_symbol');
        }
        
        // Deadline cannot be in the past
        if (date::diffDates(sql::$TODAY, $form['deadline']) < 0) {
            $this->msg->error('paymentAcceptance-error-deadlineInPast');
        }
        // Deadline must be before the starting day of the seminar
        if (date::diffDates($seminar['begin_date'], $form['deadline']) >= 0) {
        	$this->msg->error('paymentAcceptance-error-deadlineTooLate');
        }
        // You cannot move the deadline backwards
        if ($oldRecord && date::diffDates($oldRecord['deadline'], $form['deadline']) < 0) {
            $this->msg->error('paymentAcceptance-error-cannotMoveDeadlineBackwards');
            $this->viewData['paymentAcceptance']['deadline'] = $oldRecord['deadline'];
        }
        
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->renderSubview('org/paymentAcceptance/paymentAcceptanceEdit');
            return;
        }
        
        // Database validation
        $countWithSameVariableSymbol = $this->dao->queryCount(
                'SELECT count(*) FROM payment_acceptance ' .
                'WHERE organization_id = :organization_id AND variable_symbol = :variable_symbol AND seminar_id != :seminar_id',
                array(
                    'organization_id' => $this->getAuthOrg('id'), 
                    'variable_symbol' => $form['variable_symbol'], 
                    'seminar_id' => $form['seminar_id'])
        );
        if ($countWithSameVariableSymbol > 0) {
            $this->loadFormData();
            $this->msg->error('paymentAcceptance.error-variableSymbolAlreadyUsed');
            $this->renderSubview('org/paymentAcceptance/paymentAcceptanceEdit');
            return;
        }
        
        if ($form['accepts_cash'] || $form['accepts_bank_transfer']) {
            if ($oldRecord) {
                // Update the record
                $this->dao->update('payment_acceptance', $form, array('organization_id', 'seminar_id'));
            }
            else {
                // Insert the record
                $this->dao->insert('payment_acceptance', $form);
            }

            $this->msg->info('paymentAcceptance.saveSuccess', $seminar['name']);
        }
        $this->redirect('org/orgSeminar/display?id=' . $seminar['id']);
    }
}
